<template>
  <div style="width: 100%">
    <span v-if="props.showText">{{formData[prop + '_name'] || ''}}</span>
    <el-select
      v-else
      v-model="formData[prop]"
      class="cc-select"
      :allow-create="props.allowCreate"
      :filterable="props.allowCreate || (!isMobile && props.filterable)"
      :placeholder="calcPlaceholder"
      :disabled="calcDisabled"
      @change="handleChange"
      clearable
    >
      <el-option v-for="item in options"
        :key="item.key"
        :value="item.key"
        :label="item.value"
        :disabled="item.disabled === true"
      />
    </el-select>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed, inject } from 'vue';
import { useDisabled } from 'element-plus';
import { useDevice } from '@/utils/device';

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  options: [Array, String],
  allowCreate: {
    type: Boolean,
    default: false
  },
  filterable: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: '--请选择--'
  },
  showText: Boolean,
  disabled: Boolean,
});
const formData = inject('formData');
const { isMobile } = useDevice();
const options = ref([]);
const inputDisabled = useDisabled();

const init = (data) => {
  if (data.options) {
    if (Array.isArray(data.options)) {
      options.value = data.options;
    } else if (typeof data.options === 'string') {
      let optionList = [];
      data.options.split(',').forEach(item => {
        optionList.push({key: item, value: item});
      });
      options.value = optionList;
    }
  }
};

const handleChange = (event) => {
  emit('change', event);
};

const calcPlaceholder = computed(() => {
  return (inputDisabled.value || props.disabled) ? '' : props.placeholder;
});

const calcDisabled = computed(() => {
  return inputDisabled.value || props.disabled;
});

watch(() => props, (data) => {
  init(data);
}, {deep: 1});

onMounted(() => {
  init(props);
});
</script>

<style scoped>
.cc-select {
  width: 100%;
}
</style>